<?php

defined('SYSPATH') or die('Access error!');

/**
 * Cookie helper 类
 */
class Cookie
{

    public static $salt = 'kooky';
    public static $expiration = 0;
    public static $path = '/';
    public static $domain = NULL;
    public static $secure = FALSE;
    public static $httponly = FALSE;

    /**
     *  获取一个cookie
     * @param   string  cookie名字
     * @param   mixed   需要返回的值
     * @return  string
     */
    public static function get($key, $default = NULL)
    {
        if (!isset($_COOKIE[$key]))
        {
            return $default;
        }

        $cookie = $_COOKIE[$key];

        $split = strlen(Cookie::salt($key, NULL));

        if (isset($cookie[$split]) AND $cookie[$split] === '~')
        {
            list ($hash, $value) = explode('~', $cookie, 2);

            if (Cookie::salt($key, $value) === $hash)
            {
                return $value;
            }

            Cookie::delete($key);
        }

        return $default;
    }

    /**
     * 设置一个cookie
     */
    public static function set($name, $value, $expiration = NULL)
    {
        if ($expiration === NULL)
        {
            $expiration = Cookie::$expiration;
        }

        if ($expiration !== 0)
        {
            $expiration += Date::get_time();
        }

        $value = Cookie::salt($name, $value) . '~' . $value;

        return setcookie($name, $value, $expiration, Cookie::$path, Cookie::$domain, Cookie::$secure, Cookie::$httponly);
    }

    /**
     * 删除cookies
     *
     *     Cookie::delete('theme');
     *
     * @param   string   cookie名字
     * @return  boolean
     */
    public static function delete($name)
    {
        unset($_COOKIE[$name]);

        return Cookie::set($name, NULL, -86400);
    }

    /**
     * cookie安全码.
     *
     *     $salt = Cookie::salt('theme', 'red');
     *
     * @param   string   cookie名字
     * @param   string   cookie值
     */
    public static function salt($name, $value)
    {
        $agent = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : 'unknown';

        return sha1($agent . $name . $value . Cookie::$salt);
    }

}
